import { assetManager, Color, EventMouse, EventTouch, find, instantiate, Label, log, macro, Node, Prefab, Sprite } from "cc";
import { ccclass, EBlockOnceAdType, EPlatformType, EBottomAdType, NodeHelper, PropHelper, _language, EUIState, _platform, _audio, _timer, _ui, _logic, _main, CreatePrefabToEditorCC, Maths, AnimtorByTweenCC, _guide, Times, _logicLevel, _gameType } from "../../../main/script/Main";
import { AnimBaseUI } from "../../../main/script/ui/AnimBaseUI";
import { CGameData } from "../../../app/GameDefine";
import { RunUITopItem } from "./RunUITopItem";
import { EGameType } from "../../../main/script/module/define/GameTypeDefine";
import { losChannel } from "../../../app/Script/SDK/losChannel";
import { losTools } from "db://assets/app/Script/Tools/losTools";
import { ECubesType } from "db://assets/main/script/module/define/LogicDefine";
import loskc from "db://assets/app/Script/SDK/loskc";



@ccclass("RunUI")
export class RunUI extends AnimBaseUI {
	private cLabel_time: Label = null!
	private cLabel_level: Label = null!
	private cBottomBtns: Node = null!
	private cAtime: Node = null!
	private cAstep: Node = null!
	private cLabel_step: Label = null!
	private cABottoms: Node = null!
	private cATop: Node = null!
	private cLabel_level_duration: Label = null!

	private cPause: Node = null!
	public cAdds: Node = null!
	public cMerge: Node = null!
	private cALevel: Node = null!

	public cCreatePrefabToEditorCC_ratio: CreatePrefabToEditorCC = null!
	private cSprite_ratio: Sprite = null!
	private cAnimtorByTweenCC_tip: AnimtorByTweenCC = null!
	private cReset: Node = null!
	private cResetVideo: Node = null!
	private cResetText: Node = null!
	private cResetVideo_Label: Node = null!

	private _clickMergeTimes: number = 0;


	onCreate() {
		super.onCreate()
		this.blockOnceAdType = EBlockOnceAdType.None
		if (_platform.isLongScreen) {
			switch (_platform.type) {
				case EPlatformType.wx:
					this.bottomAdType = EBottomAdType.Native
					break
				case EPlatformType.web:
					this.bottomAdType = EBottomAdType.None
					break
				default:
					this.bottomAdType = EBottomAdType.Banner
					break
			}
		}
		else {
			this.bottomAdType = EBottomAdType.None
		}

		NodeHelper.setPositionY(this.cBottomBtns, _logic.getBottomY(), false)

		this.addEvent(PropHelper.EventType.CHANGE, this.onEventStepCount, this, _logic._level.step)
		this.addEvent(_gameType.EventType.PLAY_ANIM, () => {
			_audio.play("scene/audio/magic")
			this.cAnimtorByTweenCC_tip.setOpacity(1)
			this.cAnimtorByTweenCC_tip.play()
		}, this, _gameType)
		this.addEvent(_logic.EventType.MERGE_CHANGE, this.onEventMeger, this, _logic)
		this.addEvent(_logic.EventType.MAX_ID_CHANGE, this.updateRatio2, this, _logic)
	}

	protected onClose(): void {
		super.onClose()
		log("run ui 关闭")
		losChannel.instance().closeResidentBanner();
		this.unscheduleAllCallbacks()
		this._clickMergeTimes = 0;
	}
	onOpen() {
		super.onOpen();
		losChannel.instance().getChannel().doAction("所有二级界面弹出插屏", ['hw'])
		this.cResetVideo.active = true;
		this.cResetVideo_Label.active = false;
		// losChannel.instance().doAction(22, ['hw'], (enabled, val) => {
		// 	this.cResetVideo_Label.active = enabled;
		// 	this.cResetVideo.active = !enabled;
		// });

		// losChannel.instance().doAction(14, ['oppo1', 'oppo'], (enabled, val) => {
		// 	if (enabled) {
		// 		this.cResetVideo.active = false;
		// 		this.cResetText.setPosition(0, 0);
		// 		this.cResetText.setScale(1.5, 1.5);
		// 	}
		// 	else {
		// 		this.cResetVideo.active = true;
		// 		this.cResetText.setPosition(0, -20.708);
		// 		this.cResetText.setScale(1, 1);
		// 	}
		// })
		this.cReset.setPosition(291.898, 162);
		this.cAdds.setPosition(-170, 72);
		this.cMerge.setPosition(170, 72);
		const chName = losChannel.instance().channel;
		if (chName == 'xiaomi') {
			this.cReset.setPosition(291.898, 206);
		}
		_timer.clear(this, this.onLoopDownCount)
		switch (_gameType.type) {
			case EGameType.level:
				this.cATop.active = false
				this.cABottoms.active = false
				this.cALevel.active = true
				this.cAtime.active = false
				this.onEventLevel()
				this.playAnim(true)
				this.cAstep.active = false
				this.onEventStepCount()
				_timer.loop(this, this.onLoopDownCount, 1, -1, -1)
				setTimeout(() => {
					let foundTempVd = false;
					for (let data of _logic.data.datas) {
						if (data.type == ECubesType.tempVideo) {
							foundTempVd = true;
							break
						}
					}
					if (!foundTempVd) return;
					assetManager.loadBundle('scene', (err, bundle) => {
						bundle.load('prefab/ui/UnLockSoltUI', Prefab, (err, p) => {
							if (p != null) {
								let node = instantiate(p)
								node.parent = find("UICanvas/stage")
								if (node.parent.getChildByName('UnLockSolt')) {
									log('已存在bUnLockSolt，销毁')
									node.destroy()
									return;
								}
								node.name = 'UnLockSolt'
							}
						})
					})
				}, 1000)
				losChannel.instance().doAction(14, ["hw"], (enabled: boolean, val: number) => {
					if (enabled && _guide.newUserComplete) {
						loskc.chance(val / 100) && losTools.showKuangDian();
					}
				});
				break;
			case EGameType.endless:
				this.cATop.active = true
				this.cABottoms.active = true
				this.cALevel.active = false
				this.cAtime.active = false
				this.cAstep.active = false
				this.playAnim(true, () => {
					this.scene.setCubStartPos(this.cAdds.worldPosition)
					this.scene.setEndPos(
						this.cCreatePrefabToEditorCC_ratio.LayoutCC.getItemPosition(
							_logic.maxCardNumsTop.length - 1,
							true
						)
					)
				})
				this.onEventMeger()

				this.updateRatio()
				break;
		}

		this.cAnimtorByTweenCC_tip.setOpacity(0)
		log("run ui 打开")
		losChannel.instance().showResidentBanner()
		this.scheduleOnce(this.sch90, 15)
		this.scheduleOnce(this.schVivoVideo, 20);
		// this.schedule(this.sch90, 90, macro.REPEAT_FOREVER, 90)
		losChannel.instance().doAction(1, ['vivo', 'vivo1', 'oppo', 'oppo1', 'xiaomi'], (enabled, val) => {
			if (enabled) {
				const channelName = losChannel.instance().channel
				if (channelName == 'vivo' || channelName == 'oppo' || channelName == 'vivo1' || channelName == 'oppo1')
					losChannel.instance().showCustomAd(false, { top: losChannel.instance().getSysInfo().windowHeight / 2 - 300 })
				else if (channelName == 'xiaomi') {
					losChannel.instance().showCustomAd(false, { top: losChannel.instance().getSysInfo().windowHeight / 2 - 500 })
				}
			}
		})

		// losChannel.instance().doAction(2, ['hw'], (enabled, val) => {
		// 	if (enabled && loskc.chance(val / 100)) {
		// 		losChannel.instance().showCustomAd();
		// 	}
		// })
	}
	//两个计时器，一个60秒，一个30秒负责弹出插屏
	private sch40() {
		losChannel.instance().doAction(20, ['hw']);
		this.unschedule(this.sch40);
		this.scheduleOnce(this.sch40, losTools.getRandomInt(30, 40))
	}
	private schVivoVideo() {
		const nextShowTime = losTools.getRandomInt(18, 25);
		loskc.log('下一次弹插屏视频：' + new Date(Date.now() + nextShowTime * 1000).toLocaleString());
		losChannel.instance().doAction(9, ['vivo'])
		this.unschedule(this.schVivoVideo)
		this.scheduleOnce(this.schVivoVideo, nextShowTime)
	}
	private sch90() {
		let channelName = losChannel.instance().channel;
		let min = 40;
		let max = 90;
		losChannel.instance().doAction(3, ['vivo', 'vivo1', 'oppo', 'oppo1', 'xiaomi'])
		switch (channelName) {
			case 'vivo':
				min = 15;
				max = 20;
				break;
		}
		const nextShowTime = losTools.getRandomInt(min, max);
		loskc.log('下一次弹插屏时间：' + new Date(Date.now() + nextShowTime * 1000).toLocaleString());
		this.unschedule(this.sch90)
		this.scheduleOnce(this.sch90, nextShowTime)
	}

	public updateRatio() {
		if (!_gameType.isRun)
			return
		let topIndex = _logic.getTopIndex()

		this.cSprite_ratio.fillRange = topIndex / (_logic.maxCardNumsTop.length - 1)

		this.cCreatePrefabToEditorCC_ratio.render(_logic.maxCardNumsTop, RunUITopItem, (comp, data, index) => {
			comp.init(index, topIndex)
		})
	}
	/**
	 * updateRatio2
	 */
	public updateRatio2() {
		this.updateRatio()
		// const channelName = losChannel.instance().channel
		losChannel.instance().doAction(6, ['vivo', 'oppo', 'vivo1', 'oppo1', 'xiaomi'], (enabled, val) => {
			if (enabled)
				losTools.showKuangDian()
		})
		losChannel.instance().doAction(6, ['hw', 'ks2', 'ks3', 'honor'], (enabled, val) => {
			if (enabled && loskc.chance(val / 100))
				losTools.showKuangDian()
		})
		losChannel.instance().doAction(5, ['ks'], (enabled, val) => {
			if (enabled)
				losTools.showRewardBoxNew()
		})
		losChannel.instance().doAction(5, ['hw', 'ks2', 'ks3', 'honor'], (enabled, val) => {
			if (enabled && loskc.chance(val / 100))
				losTools.showRewardBoxNew()
		})
	}

	private onEventMeger() {
		NodeHelper.setOpacity(this.cMerge, _logic.hasAllMerge() ? 1 : .5)
	}

	private updateLevelTime() {
		this.cLabel_level_duration.string = Times.numMinute(_logicLevel.getSuccessTime(_logic._level.curLevel) * 1000)
	}

	private onEventStepCount() {
		let cur = _logic._level.step.cur
		this.cLabel_step.string = cur + ""
	}
	private onLoopDownCount() {
		let state = _ui.getModule(CGameData.SettingUrl).state
		if (state == EUIState.Open
			|| state == EUIState.Load)
			return
		state = _ui.getModule(CGameData.SuccessUrl).state
		if (state == EUIState.Open
			|| state == EUIState.Load)
			return
		state = _ui.getModule(CGameData.FailUrl).state
		if (state == EUIState.Open
			|| state == EUIState.Load)
			return

		this.updateLevelTime()
	}

	private onEventLevel() {
		switch (_gameType.type) {
			case EGameType.level:
				this.cLabel_level.string = _language.replace(40014, _logic._level.curLevel + "")
				break
		}
	}

	private onClickAdds() {
		if (_guide.newUserComplete || _guide.newUserIndex > _guide.getOnceLastByIndex(2))
			_logic.adds()
		else
			_logic.addsGuide()
	}

	private onClickMerge() {
		_logic.merge();

		this._clickMergeTimes++;
		console.log("点击合并次数：", this._clickMergeTimes);
		losChannel.instance().doAction(17, ['hw'], (enabled, val) => {
			if (val > 0 && this._clickMergeTimes % val == 0) {
				losChannel.instance().showCustomAd();
			}
		})

		if (NodeHelper.getOpacity(this.cMerge) == 1) {
			losChannel.instance().doAction(13, ['vivo1', 'oppo', 'oppo1'], (enabled, val) => {
				if (enabled && loskc.chance(val / 100)) {
					losChannel.instance().showVideo();
				}
			})
		}
	}

	public onClickReset() {
		let res = _logic.resetAfger()
		if (res.datas.length == 0) {
			// _ui.tip("无牌")
			return
		}

		losChannel.instance().showVideo({
			sucCall: () => {
				_logic.reset(res)
			}, failCall: () => { }, endCall: () => { }, posName: "video"
		})
	}

	private onClickPause() {
		_ui.open(CGameData.SettingUrl)
	}

	protected onTouchStart(e: EventTouch) {
		if (this.scene)
			this.scene.touchStart(e)
	}

	protected onTouchEnd(e: EventTouch) {
		if (this.scene)
			this.scene.touchEnd(e)
	}

	protected onTouchCancel(e: EventTouch) {
		if (this.scene)
			this.scene.touchCancel(e)
	}

	protected onTouchMove(e: EventTouch) {
		if (this.scene)
			this.scene.touchMove(e)
	}

	protected onMouseWheel(e: EventMouse) {
		if (this.scene)
			this.scene.mouseWheel(e)
	}

}
